<?php
// +----------------------------
// | Created by PhpStorm
// +----------------------------
// | Author: YnnSon
// +----------------------------
namespace app\api\model;

use think\Db;

class SubscribeCode extends BaseModel
{
    /**
     * @Desc 获取预约码并更新数据
     * @param $company_id
     * @param $today
     *
     * @return string|null
     */
    public static function getAndUpdateData($company_id, $today)
    {
        $data = self::get(['company_id' => $company_id]);
        if(!$data){
            return null;
        }
        $date = $data->getAttr('date');
        $code = $data->getAttr('code');
        $company_abbr = Db::name('company')->where('id', '=', $company_id)->value('company_abbr');
        // 比表中的日期大, code重新计数, 日期改为今天
        if ($today > $date) {
            $code = 1;
            $updateData = [
                'code' => $code + 1, // 2
                'date' => $today, // 2020-09-01
            ];
        } else {
            $updateData = [
                'code' => $code + 1, // 2
            ];
        }
        self::update($updateData, ['company_id' => $company_id]);
        $value = str_pad($code, 3, '0', STR_PAD_LEFT); // 用0填充字符串到指定长度(3位)
        return $company_abbr . $value;
    }
}